package io.github.mengfly.kvstore.util;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 文字压缩工具类
 *
 * @author wangp
 */
public class Compressor {

    public static byte[] compress(String str) {
        if (str == null) {
            return new byte[0];
        }
        Deflater compressor = new Deflater();

        byte[] keyBytes = str.getBytes(StandardCharsets.UTF_8);
        compressor.setInput(keyBytes);
        compressor.finish();

        byte[] output;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream(keyBytes.length)) {
            byte[] compressBytes = new byte[keyBytes.length];
            while (!compressor.finished()) {
                final int deflate = compressor.deflate(compressBytes);
                bos.write(compressBytes, 0, deflate);
            }
            output = bos.toByteArray();
        } catch (Exception ignored) {
            output = new byte[0];
        }
        compressor.end();
        return output;
    }

    public static String deCompress(byte[] input) {
        if (input.length == 0) {
            return null;
        }
        Inflater inflater = new Inflater();
        inflater.setInput(input);

        String result;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length)) {
            byte[] buff = new byte[1024];
            while (!inflater.finished()) {
                int count = inflater.inflate(buff);
                baos.write(buff, 0, count);
            }
            byte[] output = baos.toByteArray();
            result = new String(output, StandardCharsets.UTF_8);
        } catch (Exception e) {
            result = "";
        }
        inflater.end();

        return result;
    }

    public static byte crc32(byte[] key, byte[] value) {
        CRC32 crc32 = new CRC32();
        crc32.update(key);
        crc32.update(value);
        return (byte) crc32.getValue();
    }


}
